function empty(value) {
    return value === undefined || value === null || value === "";
}

// 设置ajax
$.ajaxSetup({
    headers: {
        "X-CSRF-TOKEN": $("meta[name='csrf-token']").attr("content")
    },
    beforeSend: function () {
        NProgress.start();
    },
    complete: function () {
        NProgress.done();
    }
});

var mixLoading = null;

/**
 * ajax 自定义的ajax 处理
 * @param params
 * @param message
 * @returns {*}
 */
function ajax(params, message) {
    mixLoading = layer.load();
    return $.ajax(params)
        .always(function () {
            layer.close(mixLoading);
        }).fail(function () {
            layer.msg(message, {icon: 5});
        });
}

/**
 * 发送laravel 的请求
 * @param params
 * @param message
 * @returns {*}
 */
function getLaravelRequest(params, message) {
    mixLoading = layer.load();
    return $.ajax(params)
        .always(function () {
            layer.close(mixLoading);
        }).fail(function (response) {
            var html = '';
            if (response.responseJSON) {
                html += response.responseJSON.message + " <br/>";
                for (var i in response.responseJSON.errors) {
                    html += response.responseJSON.errors[i].join(";") + "<br/>";
                }
            } else {
                html = message;
            }

            layer.msg(html, {icon: 5});
        });
}

/**
 * 获取值
 *
 * @return mixed
 * @param arrValue
 * @param key
 * @param defaultValue
 */
function getValue(arrValue, key, defaultValue) {
    if (!arrValue || typeof arrValue !== 'object') {
        return defaultValue;
    }

    if (typeof key === "string") {
        var index = key.lastIndexOf(".");
        if (key.lastIndexOf(".") !== -1) {
            arrValue = getValue(arrValue, key.substr(0, index), defaultValue);
            key = key.substr(index + 1);
        }
    }

    if (!arrValue || typeof arrValue !== 'object') {
        return defaultValue;
    }

    if (key in arrValue) {
        return arrValue[key];
    }

    return arrValue[key] ? arrValue[key] : defaultValue;
}

function createHiddenInput(uid, data) {
    return '<input class="vue-hide-input" id="url-' + uid + '" name="resources[' + uid + '][url]" type="hidden" value="' + data.url + '"/>' +
        '<input class="vue-hide-input" id="type-' + uid + '" name="resources[' + uid + '][type]" type="hidden" value="' + data.type + '"/>';
}

function vueUploadMulti($select, limit) {
    return new Vue({
        el: "#vue-upload",
        data: {
            headers: {
                "X-CSRF-TOKEN": $("meta[name='csrf-token']").attr("content")
            },
            list: [],
            limit: limit || 9,
            disabled: false,
        },
        methods: {
            success(response, file) {
                if (response.code === 0) {
                    this.$message.success('上传成功');
                    $select.append(createHiddenInput(file.uid, response.data));
                } else {
                    this.$message.error('上传失败：' + (response.msg || '未知错误'));
                    this.$children[0].clearFiles();
                }
            },
            remove: function (file, fileList) {
                $("#url-" + file.uid).remove();
                $("#type-" + file.uid).remove();
            },
            error: function (err, file, fileList) {
                this.$message.error('服务器繁忙，请稍后再试');
            }
        }
    });
}


function vueUpload(select, params) {
    params = params || {delete: 'delete-image'}
    return new Vue({
        el: "#vue-upload",
        data: {
            headers: {
                "X-CSRF-TOKEN": $("meta[name='csrf-token']").attr("content")
            },
            list: [],
            disabled: false,
        },
        methods: {
            success(response, file, fileList) {
                if (response.code === 0) {
                    this.$message.success('上传成功');
                    this.handleUrl(response.data.url)
                    if (fileList.length > 1) {
                        this.list = [fileList.pop()]

                        if (fileList.length !== 0) {
                            fileList.forEach(this.handleRemove)
                        }

                        this.$children[0].clearFiles();
                    }
                } else {
                    this.$message.error('上传失败：' + (response.msg || '未知错误'));
                    this.$children[0].clearFiles();
                }
            },
            remove: function (file) {
                this.handleRemove(file)
                this.handleUrl('')
            },
            error: function (err, file, fileList) {
                this.$message.error('服务器繁忙，请稍后再试');
            },
            handleRemove: function (file) {
                var url = getValue(file, 'response.data.path') ? file.response.data.url : file.url;
                if (url && params.delete) {
                    $.ajax({
                        type: "POST",
                        url: params.delete,
                        data: {url: url},
                        dataType: "json"
                    })
                }
            },
            handleUrl: function (url) {
                if (getValue($(select).get(0), 'tagName') === "IMG") {
                    $(select).prop("src", url);
                } else {
                    $(select).val(url);
                }
            }
        }
    });
}

// 联动处理
$(document).on("change", "select[data-change=true]", function () {
    var $child = $($(this).data("child"));
    var v = $(this).val();
    if ($child.length > 0) {
        var html = '<option value="" selected>' + $child.attr("placeholder") + '</option>',
            name = $child.data("child-name") || $(this).attr('name'),
            labelKey = $child.data("label-key") || 'name',
            valueKey = $child.data("value-key") || 'id',
            data = {},
            func = $child.data('func');
        if (!func) {
            func = function (item) {
                return {
                    label: getValue(item, labelKey),
                    value: getValue(item, valueKey)
                }
            }
        }
        data[name] = v;
        if (v <= 0) {
            $child.html(html);
        } else {
            $.ajax({
                type: "get",
                data: data,
                dataType: "json",
                url: $child.data("url"),
            }).done(function (json) {
                if (json.code === 0) {
                    for (var i in json.data) {
                        var options = func(json.data[i])
                        html += "<option value='" + getValue(options, 'value') + "'>" + getValue(options, 'label') + "</option>"
                    }
                    $child.html(html)
                }
            });
        }
    }
});

// 表单提交
$(document).on("submit", "form[data-ajax=true]", function (evt) {
    evt.preventDefault();
    $self = $(this);

    // 验证
    if ($self.data("validate") && !$self.validate().form()) {
        return false;
    }

    // 之前的操作
    if ($self.data("before") && $self.data("before")() === false) {
        return false;
    }

    // 确定
    var confirmMessage = $self.data('confirm');
    var data = $self.serializeArray();

    if ($self.data("beforeData")) {
        data = $self.data("beforeData")(data)
    }
    var handle = function () {
        // 处理
        getLaravelRequest({
            url: $self.attr("action"),
            data: data,
            type: "post",
            dataType: "json",
        }, '服务器繁忙，请稍后再试...').done(function (json) {
            layer.msg(json.msg, {icon: json.code === 0 ? 6 : 5});
            !$self.data('no-reset') && $self.get(0).reset();
        })
    }

    if (confirmMessage) {
        layer.confirm(confirmMessage, handle)
    } else {
        handle()
    }
});

$(document).on("click", ".input-hide>.tip-block", function (evt) {
    evt.preventDefault();
    $(this).remove()
});
